package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class HostRequestProcessor extends Thread {

    private Socket socket;
    private Host host;

    public HostRequestProcessor(Socket socket, Host host) {
        this.socket = socket;
        this.host = host;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            // 静态资源处理
            Map<String, ServletWrapper> wrapperMap = host.getContext().getWrapperMap();
            String url = request.getUrl();
            String appName = url.split("/")[1];
            ServletWrapper wrapper = wrapperMap.get(appName);
            String urlPattern = url.substring(1);
            if(wrapper.getStaticFile().get(urlPattern) != null) {
                response.outputHtml(wrapper.getStaticFile().get(urlPattern));
            }else{
                urlPattern = url.substring(appName.length());
                // 动态资源servlet请求
                HttpServlet httpServlet =wrapper.getServletMap().get(urlPattern);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
